package com.wmh.baseservice.merchant.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.redis.utils.RedisUtil;
import com.wmh.baseservice.common.utils.*;
import com.wmh.baseservice.common.utils.encrypt.Base64Util;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.pojo.SortWay;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.common.utils.upload.service.CosService;
import com.wmh.baseservice.merchant.pojo.MerchantFreightTemplate;
import com.wmh.baseservice.merchant.pojo.MerchantGroupGoods;
import com.wmh.baseservice.merchant.pojo.MerchantGroupGoodsPrice;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.*;
import com.wmh.baseservice.skd.service.SkdGoodsSpecService;
import com.wmh.baseservice.system.pojo.SysLocation;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.pojo.vo.SysLocationTreeVO;
import com.wmh.baseservice.system.service.SysLocationService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.pojo.UsAddress;
import com.wmh.baseservice.user.pojo.UsAfterSaleApply;
import com.wmh.baseservice.user.pojo.UsGroupGoodsOrder;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.service.UsAddressService;
import com.wmh.baseservice.user.service.UsAfterSaleApplyService;
import com.wmh.baseservice.user.service.UsGroupGoodsOrderService;
import com.wmh.baseservice.user.service.UsInfoService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author wmh generator
 * @since 2022-03-03
 */
@Api(tags = "商家端-团购商品相关接口")
@Validated
@RestController
@RequestMapping(value = "merchant/merchantGroupGoods", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
@Slf4j
public class MerchantGroupGoodsController {

    @Resource
    private MerchantGroupGoodsService merchantGroupGoodsService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantGroupGoodsPriceService merchantGroupGoodsPriceService;
    @Resource
    private UsGroupGoodsOrderService usGroupGoodsOrderService;
    @Resource
    private UsAddressService usAddressService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private SysLocationService sysLocationService;

    @Resource
    private MerchantFreightTemplateService merchantFreightTemplateService;
    @Resource
    private UsAfterSaleApplyService usAfterSaleApplyService;
    @Resource
    private SysParamsService sysParamsService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CosService cosService;

    /**
     * @param sort 1 正序 -1 倒叙
     */
    @ApiOperation("列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "name", value = "标题", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "categoryId", value = "分类id", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "startTime", value = "起始日期", required = false),
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "endTime", value = "结束日期", required = false)
    })
    public String list(PageInfo pageInfo, String startTime, String endTime, String name, Long categoryId, Integer sort) {
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            id = parentInfo.getId();
        }
        // 设置分页排序规则
        PageUtil.setPageSortRoles(pageInfo, sort, "create_time");
        //执行分页辅助工具
        Long finalId = id;
        PageResult<MerchantGroupGoods> pageResult = new PageUtil<MerchantGroupGoods>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantGroupGoods.MERCHANT_ID, finalId);
            if (StrUtil.isNotBlank(name)) {
                queryWrapper.like(MerchantGroupGoods.TITLE, name);
            }
            if (categoryId != null) {
                queryWrapper.eq(MerchantGroupGoods.CATEGORY_ID, categoryId);
            }
            if (StrUtil.isNotBlank(startTime) && StrUtil.isNotBlank(endTime)) {
                queryWrapper.ge(MerchantGroupGoods.START_TIME, startTime);
                queryWrapper.le(MerchantGroupGoods.END_TIME, endTime);
            }
            queryWrapper.ne(MerchantGroupGoods.STATUS, -2);
            merchantGroupGoodsService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

//    @ApiOperation("添加商品")
//    @PostMapping("addGroupGoods")
//    @ParameterVerify(notNull = {"title", "img", "categoryId", "overview", "inventory", "originalPrice", "priceList", "hasSpec", "startTime", "endTime", "unit", "type"})
//    public String addGroupGoods(String title, Long categoryId, String avatar, String img, String overview, String content, @RequestBody MultipartFile video,
//                                Integer inventory, Long urlId, String originalPrice, Integer hasSpec, String startTime, String endTime, String commission,
//                                Long freightId, String unit, String buyUnit, String priceList, String areaList, Integer type, String selfMentionAddress,
//                                Integer hasFreeShipping, String latLng, String locationIds, Integer isAutoShelving, Integer autoShelvingTime, String app) throws IOException {
//        if (hasSpec != 1 && hasSpec != -1) {
//            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//        }
//        Long id = (Long) request.getAttribute("id");
//        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
//        if (merchantInfo.getParentId() != -1) {
//            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
//            id = parentInfo.getId();
//        }
//
//        //系统控制是否需要缴纳保证金
//        SysParams sysParams = sysParamsService.getByIdForUpdate(17L);
//        if (CommUtil.checkNull(sysParams) && "1".equals(sysParams.getValue())) {
//            if (merchantInfo.getMargin().compareTo(BigDecimal.ZERO) <= 0) {
//                return ReturnBody.error("保证金未缴纳或金额小于0元，请先到小程序商家后台处缴纳保证金再上架团购商品");
//            }
//        }
//        //查询运费模板
//        if (type == 2 || type.toString().contains("1") && hasFreeShipping == -1) {
//            //查询运费模板
//            if (CommUtil.checkNull(freightId) && freightId != -1) {
//                MerchantFreightTemplate merchantFreightTemplate = merchantFreightTemplateService.getByIdForUpdate(freightId);
//                if (!CommUtil.checkNull(merchantFreightTemplate)) {
//                    return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//                }
//            }
//        }
//
//        JSONArray imgList = new JSONArray();
//        JSONObject object = new JSONObject();
//        object.put("priceList", priceList);
//        object.put("areaList", areaList);
//
//        MerchantGroupGoods merchantGroupGoods = new MerchantGroupGoods().setTitle(title).setCategoryId(categoryId).setOverview(overview)
//                .setInventory(inventory).setUrlId(urlId).setMerchantId(id).setOriginalPrice(new BigDecimal(originalPrice)).setHasSpec(hasSpec)
//                .setStartTime(startTime).setEndTime(endTime).setFreightId(freightId).setUnit(unit).setBuyUnit(buyUnit).setType(type)
//                .setSelfMentionAddress(selfMentionAddress).setHasFreeShipp(hasFreeShipping).setSnapshot(object.toJSONString())
//                .setCommission(new BigDecimal(commission).compareTo(BigDecimal.ZERO) == 0 ? null : new BigDecimal(commission)).setLocationIds(locationIds)
//                .setIsAutoShelving(isAutoShelving).setAutoShelvingTime(autoShelvingTime);
//        if (type == 2 || type.toString().contains("0")) {
//            if (!CommUtil.checkNull(latLng)) {
//                return ReturnBody.error("请手动定位商品自提地址");
//            }
//            merchantGroupGoods.setSelfMentionAddress(selfMentionAddress).setLatLng(latLng);
//        }
//        if (type == 2 || type.toString().contains("3")) {
//            if (!CommUtil.checkNull(locationIds)) {
//                return ReturnBody.error("请选择支持配送的区域");
//            }
//            merchantGroupGoods.setType(type);
//        }
//        if (!CommUtil.checkNull(urlId)) {
//            urlId = UUIDUtil.getTimeId();
//            merchantGroupGoods.setUrlId(urlId);
//        }
//
//        //处理团购商品价格
//        List<JSONObject> priceArray = JSONArray.parseArray(priceList, JSONObject.class);
//        if (priceArray.size() == 0) {
//            return ReturnBody.error("请添加拼单商品价格档位");
//        }
//        // 判断商品优惠档位是否超标
//        merchantGroupGoodsService.isPreferentialOverweight(hasSpec, inventory, merchantGroupGoods.getOriginalPrice(), priceArray);
//
//        if (!CommUtil.checkNull(app)) {
//            if (CommUtil.checkNull(avatar) && avatar.contains("base64")) {
//                String url = Base64Util.generateImage("main_image/" + urlId, avatar);
//                if (!CommUtil.checkNull(url)) {
//                    return ReturnBody.error("图片上传失败!");
//                }
//                merchantGroupGoods.setAvatar(PathUtil.COS_DOMAIN + "/main_image/" + urlId + "/" + url);
//            }
//        }
//
//        if (CommUtil.checkNull(img)) {
//            JSONArray array = JSONArray.parseArray(img);
//            Long finalUrlId = urlId;
//            array.forEach(item -> {
//                String itemImg;
//                itemImg = Base64Util.generateImage("rotating_chart/" + finalUrlId, item.toString());
//                if (!CommUtil.checkNull(itemImg)) {
//                    throw new ServiceException("图片上传失败!");
//                }
//                imgList.add(PathUtil.COS_DOMAIN + "rotating_chart/" + finalUrlId + "/" + itemImg);
//            });
//            merchantGroupGoods.setImg(imgList.toJSONString());
//            if (CommUtil.checkNull(app)) {
//                //测试主图路径是否存在
//                imgList.forEach(item -> {
//                    try {
//                        HttpRequestUtil.sendGet("https://www.tdtye.com" + item.toString(), "");
//                        merchantGroupGoods.setAvatar(item.toString());
//                    } catch (Exception e) {
//                        LogUtil.warn("{}当前图片已无法访问，寻找下一张作为主图", item);
//                    }
//                });
//            }
//        }
//        if (!CommUtil.checkNull(content)) {
//            content = "<p></p>";
//        }
//        if (CommUtil.checkNull(app) && CommUtil.checkNull(content)) {
//            //轮播图插入详情中
//            Document document = new Document("");
//            imgList.forEach(item -> {
//                document.append(String.format("<img src=%s></img>", item.toString()));
//            });
//            content = PathUtil.subImgPathPrefix(content);
//            Document dom = Jsoup.parse(content);
//            dom.select("p").append(document.html());
//            Elements imgTag = dom.select("img");
//            imgTag.forEach(item -> item.attr("style", "max-width:100%"));
//            content = dom.body().toString().replace("<body>\n", "").replace("\n</body>", "");
//
//        }
//        merchantGroupGoods.setContent(content);
//        if (CommUtil.checkNull(video)) {
//            // 生成视频唯一文件名
//            String videoUniqueFileName = CommUtil.generateUniqueFileName(Objects.requireNonNull(video.getOriginalFilename()));
//            String upload = cosService.upload(video.getBytes(), "video/" + videoUniqueFileName);
//            if (CommUtil.checkNull(upload)) {
//                merchantGroupGoods.setVideo(PathUtil.COS_DOMAIN + upload);
//            }
//        }
//        merchantGroupGoodsService.add(merchantGroupGoods, priceArray, areaList);
//        return ReturnBody.success();
//    }

//    @ApiOperation("修改商品")
//    @PostMapping("updateGoods")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
//    })
//    @ParameterVerify(notNull = {"id", "title", "categoryId", "overview", "content", "inventory", "priceList", "unit"})
//    public String updateGoods(Long id, String title, Long categoryId, String avatar, String img, String overview, String content,
//                              MultipartFile video, Integer inventory, BigDecimal originalPrice, Boolean hasVideo, Integer hasSpec,
//                              String startTime, String endTime, Long freightId, String unit, String buyUnit, String priceList, String areaList,
//                              Integer type, String selfMentionAddress, Integer hasFreeShipping, String latLng, BigDecimal commission,
//                              String locationIds, Integer isAutoShelving, Integer autoShelvingTime, String app) throws IOException {
//
//        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
//        if (!CommUtil.checkNull(merchantGroupGoods)) {
//            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//        }
//        Long merchantId = (Long) request.getAttribute("id");
//        CommUtil.checkNull(merchantGroupGoods.getMerchantId(), merchantId);
//        //更新时间
//        merchantGroupGoods.setUpdateTime(null);
//        // 如果是上架状态对修改做限制
//        if (merchantGroupGoods.getStatus().equals(0)) {
//            // 设置新库存
//            merchantGroupGoods.setInventory(inventory);
//            //处理静态资源
//            merchantGroupGoods = staticManage(avatar, merchantGroupGoods, img, video, hasVideo, content, app);
//            //赋值剩余允许参数
//            merchantGroupGoods.setTitle(title).setOverview(overview);
//            merchantGroupGoodsService.weakUpdateGroupGoods(merchantGroupGoods, JSONArray.parseArray(priceList, JSONObject.class));
//            return ReturnBody.success();
//        }
//
//        //查询运费模板
//        if (type == 1 || type == 2 && hasFreeShipping == -1) {
//            if (CommUtil.checkNull(freightId) && freightId != -1) {
//                MerchantFreightTemplate merchantFreightTemplate = merchantFreightTemplateService.getByIdForUpdate(freightId);
//                if (!CommUtil.checkNull(merchantFreightTemplate)) {
//                    return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//                }
//            }
//        }
//        if (type == 1 || type == 2) {
//            if (!CommUtil.checkNull(latLng)) {
//                return ReturnBody.error("请手动定位商品自提地址");
//            }
//            merchantGroupGoods.setSelfMentionAddress(selfMentionAddress).setLatLng(latLng);
//        }
//        if (type == 2 || type == 3) {
//            if (!CommUtil.checkNull(locationIds)) {
//                return ReturnBody.error("请选择支持配送的区域");
//            }
//            merchantGroupGoods.setType(type);
//            merchantGroupGoods.setLocationIds(locationIds);
//        }
//        //处理团购商品价格
//        List<JSONObject> priceArray = JSONArray.parseArray(priceList, JSONObject.class);
//        if (priceArray.isEmpty()) {
//            return ReturnBody.error("请添加拼单商品价格档位");
//        }
//
//        // 判断商品优惠档位是否超标
//        merchantGroupGoodsService.isPreferentialOverweight(hasSpec, inventory, originalPrice, priceArray);
//
//        //静态资源处理
//        merchantGroupGoods = staticManage(avatar, merchantGroupGoods, img, video, hasVideo, content, app);
//
//        //4.对剩下的参数进行赋值
//        JSONObject object = new JSONObject();
//        object.put("priceList", priceList);
//        object.put("areaList", areaList);
//        merchantGroupGoods.setTitle(title).setCategoryId(categoryId).setOverview(overview).setInventory(inventory).setOriginalPrice(originalPrice)
//                .setStartTime(startTime).setEndTime(endTime).setUnit(unit).setBuyUnit(buyUnit)
//                .setFreightId(freightId).setType(type).setSelfMentionAddress(selfMentionAddress).setHasFreeShipp(hasFreeShipping)
//                .setSnapshot(object.toJSONString()).setLatLng(latLng).setIsAutoShelving(isAutoShelving).setAutoShelvingTime(autoShelvingTime).setUpdateTime(null);
//        if (commission.compareTo(BigDecimal.ZERO) == 0) {
//            merchantGroupGoods.setCommission(null);
//        } else {
//            merchantGroupGoods.setCommission(commission);
//        }
//        merchantGroupGoodsService.updateGroupGoods(merchantGroupGoods, priceArray, hasSpec, areaList);
//        return ReturnBody.success();
//    }

    public MerchantGroupGoods staticManage(String avatar, MerchantGroupGoods merchantGroupGoods, String img, MultipartFile video, boolean hasVideo, String content, String app) throws IOException {
        //1.主图处理
        if (CommUtil.checkNull(avatar)) {
            if (avatar.contains("base64")) {
                FileUtil.delete(merchantGroupGoods.getAvatar());
                String url = Base64Util.generateImage("main_image/" + merchantGroupGoods.getUrlId(), avatar);
                if (!CommUtil.checkNull(url)) {
                    throw new ServiceException("图片上传失败!");
                }
                merchantGroupGoods.setAvatar(PathUtil.COS_DOMAIN + "main_image/"
                        + merchantGroupGoods.getUrlId() + "/" + url);
            } else {
                merchantGroupGoods.setAvatar(avatar);
            }
        }

        //2.轮播图处理
        JSONArray imgArray = new JSONArray();
        List<String> removeList = null;
        if (CommUtil.checkNull(img)) {
            //2.1如果图片列表包含base64新上传的编码，则遍历每一个，如果是路径，取出放在上面的数组中，如果是base64，则保存后再存入数组
            JSONArray array = JSONArray.parseArray(img);
            array.forEach(item -> {
                String url = String.valueOf(item);
                if (url.contains("base64")) {
                    url = Base64Util.generateImage("rotating_chart/" + merchantGroupGoods.getUrlId(), item.toString());
                    if (!CommUtil.checkNull(url)) {
                        throw new ServiceException("图片上传失败");
                    }
                }
                // 判断图片是否新上传的, 如果原数据库图片则无需改动, 如果是新上传的图片则添加图片路径
                if (url.startsWith("https:")) {
                    imgArray.add(url);
                } else {
                    imgArray.add(PathUtil.COS_DOMAIN + "rotating_chart/" + merchantGroupGoods.getUrlId() + "/" + url);
                }
            });

            //比较然后判断
            if (CommUtil.checkNull(merchantGroupGoods.getImg())) {
                removeList = FileUtil.getList(merchantGroupGoods.getImg(), imgArray);
                if (!removeList.isEmpty()) {
                    removeList.forEach(FileUtil::delete);
                }
            }
            merchantGroupGoods.setImg(imgArray.toJSONString());
            if (CommUtil.checkNull(app)) {
                //测试主图路径是否存在
                imgArray.forEach(item -> {
                    try {
                        HttpRequestUtil.sendGet("https://www.tdtye.com" + item.toString(), "");
                        merchantGroupGoods.setAvatar(item.toString());
                    } catch (Exception e) {
                        LogUtil.warn("{}当前图片已无法访问，寻找下一张作为主图", item);
                    }
                });
            }
        }
        //2.2轮播图为空设置为null保证修改的时候可上传
        if (!CommUtil.checkNull(img) || img.equals("[\"\"]")) {
            merchantGroupGoods.setImg(null);
        }

        //3.视频处理
        if (CommUtil.checkNull(video)) {
            //3.1删除之前的视频
            if (CommUtil.checkNull(merchantGroupGoods.getVideo())) {
                FileUtil.delete(merchantGroupGoods.getVideo());
            }
            // 生成视频唯一文件名
            String videoUniqueFileName = CommUtil.generateUniqueFileName(Objects.requireNonNull(video.getOriginalFilename()));
            String upload = cosService.upload(video.getBytes(), "video/" + videoUniqueFileName);

            if (CommUtil.checkNull(upload)) {
                merchantGroupGoods.setVideo(PathUtil.COS_DOMAIN + upload);
            }
        } else {
            //3.4没有视频,如果之前有视频则删除视频文件
            if (CommUtil.checkNull(merchantGroupGoods.getVideo()) && !hasVideo) {
                FileUtil.delete(merchantGroupGoods.getVideo());
                merchantGroupGoods.setVideo(null);
            }
        }
        //3.2比较前后html是否一致
//        if (CommUtil.checkNull(content)) {
//            content = PathUtil.subImgPathPrefix(content);
//            List<String> imgList = FileUtil.getImgElementList(merchantGroupGoods.getContent(), content);
//            if (imgList.size() != 0) {
//                //3.3删除富文本删除的图片
//                imgList.forEach(item -> FileUtil.delete(item));
//            }
//        }
        if (CommUtil.checkNull(app) && CommUtil.checkNull(content)) {
            //轮播图插入详情中
            Document document = new Document("");
            imgArray.forEach(item -> {
                //判断之前的content是否有包含当前的img，如果有则不添加
                if (!merchantGroupGoods.getContent().contains(item.toString())) {
                    document.append(String.format("<img src=%s></img>", item.toString()));
                }
            });
            content = PathUtil.subImgPathPrefix(content);
            Document dom = Jsoup.parse(content);
            dom.select("p").append(document.html());
            Elements imgTag = dom.select("img");
            List<String> finalRemoveList = removeList;
            imgTag.forEach(item -> {
                for (String s : finalRemoveList) {
                    if (item.toString().contains(s)) {
                        item.remove();
                    }
                }
                item.attr("style", "max-width:100%");
            });
            content = dom.body().toString().replace("<body>\n", "").replace("\n</body>", "");
        }
        Document document = Jsoup.parse(content);
        Elements imgList = document.select("img");
        Map<String, Object> map = new HashMap<>();
        imgList.forEach(item -> {
            if (map.containsKey(item.toString())) {
                item.remove();
            } else {
                map.put(item.toString(), item.toString());
            }
        });
        content = document.body().toString().replace("<body>\n", "").replace("\n</body>", "");
        merchantGroupGoods.setContent(content);
        return merchantGroupGoods;
    }

    @ApiOperation("图片上传")
    @PostMapping("uploadImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String uploadImg(MultipartFile[] file, Long urlId) {
        JSONObject object = new JSONObject();
        Long timeId;
        //生成随机id文件夹
        if (CommUtil.checkNull(urlId)) {
            timeId = urlId;
        } else {
            timeId = UUIDUtil.getTimeId();
        }
        List<String> uploads = FileUtil.uploads("groupGoodsM/" + timeId, file, "file");
        if (!CommUtil.checkNull(uploads)) {
            return ReturnBody.error("图片上传错误");
        }
        //返回随机id，前端添加商品时传给数据库存储该文件夹字段，方便后面删除商品的时候把图片一起删除
        object.put("uploads", uploads);
        object.put("id", timeId);
        return ReturnBody.success(object);
    }

    @ApiOperation("删除图片")
    @PostMapping("deleteImg")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String deleteImg(String array) {
        JSONArray jsonArray = JSONArray.parseArray(array);
        jsonArray.forEach(item -> {
            FileUtil.delete(item.toString());
        });
        return ReturnBody.success();
    }


    @ApiOperation("详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "团购商品id", required = false),
    })
    public String detail(Long id) {
        JSONObject object = new JSONObject(true);
        //商品信息
        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
        LogUtil.info("merchantGroupGoods : {}", merchantGroupGoods);
        object.put("merchantGroupGoods", merchantGroupGoods);
        //优惠价格
        List<MerchantGroupGoodsPrice> merchantGroupGoodsPrices = merchantGroupGoodsPriceService.listForUpdate(new QueryWrapper<MerchantGroupGoodsPrice>().eq(MerchantGroupGoodsPrice.GROUP_GOODS_ID, id));
        object.put("merchantGroupGoodsPrices", merchantGroupGoodsPrices);
        return ReturnBody.success(object);
    }

    @ApiOperation("上下架")
    @PostMapping("updateStatus")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String updateStatus(Long id, Integer down) throws ParseException {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantGroupGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        CheckUtil.merchantCheck(merchantGroupGoods.getMerchantId(), merchantId);
        Integer status = merchantGroupGoods.getStatus();
        // 是否正在拼团
        if (status == 0) {
            List<UsGroupGoodsOrder> list = usGroupGoodsOrderService.list(new QueryWrapper<UsGroupGoodsOrder>()
                    .ne(UsGroupGoodsOrder.STATUS, -1)
                    .eq(UsGroupGoodsOrder.GROUP_GOODS_ID, merchantGroupGoods.getId())
                    .eq(UsGroupGoodsOrder.BATCH, merchantGroupGoods.getBatchNum()));
            if (!list.isEmpty() && (!CommUtil.checkNull(down) || down == 0)) {
                return ReturnBody.error("当前商品已有用户下单");
            }
            merchantGroupGoodsService.down(list, merchantGroupGoods);
            // 删除拼团定时时间
            merchantGroupGoodsService.removeGroupGoodsOverTiming(merchantGroupGoods);
            //给退款用户批量发消息，包括系统消息和聊天消息
            return ReturnBody.success();
        } else if (status == -1) {
            LocalDateTime endTime = DateFormatTemplate.paresDate(merchantGroupGoods.getEndTime());
            if (endTime.isBefore(LocalDateTime.now(DateFormatTemplate.ZONE_SHANGHAI))) {
                return ReturnBody.error("当前商品团购时间已过期,请重新设置后上架");
            }
            // 设置拼团结束时间
            merchantGroupGoodsService.setGroupGoodsOverTiming(merchantGroupGoods);
            // 更新批号
            merchantGroupGoods.setBatchNum(merchantGroupGoods.getBatchNum() + 1);
            merchantGroupGoods.setStatus(0);
        }
        if (!merchantGroupGoodsService.updateById(merchantGroupGoods)) {
            return ReturnBody.error(ResultCodeInfo.SERVICE_EXCEPTION);
        }
        return ReturnBody.success();
    }


    @ApiOperation("逻辑删除")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
    })
    @ParameterVerify(notNull = "id")
    public String remove(Long id) {
        Long merchantId = (Long) request.getAttribute("id");
        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantGroupGoods)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        CheckUtil.merchantCheck(merchantGroupGoods.getMerchantId(), merchantId);
        if (merchantGroupGoodsService.isSpellGrouping(merchantGroupGoods.getId())) {
            throw new ServiceException("该商品正在拼团中,请待拼团结算后删除");
        }
        merchantGroupGoods.setStatus(-2);
        if (!merchantGroupGoodsService.updateById(merchantGroupGoods)) {
            throw new ServiceException();
        }
        return ReturnBody.success();
    }

//    @ApiOperation("物理删除")
//    @PostMapping("remove")
//    @ApiImplicitParams({
//            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
//    })
//    @ParameterVerify(notNull = "id")
//    public String delete(Long id) {
//        Long merchantId = (Long) request.getAttribute("id");
//        MerchantGroupGoods merchantGroupGoods = merchantGroupGoodsService.getByIdForUpdate(id);
//        if (!CommUtil.checkNull(merchantGroupGoods)) {
//            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
//        }
//        CheckUtil.merchantCheck(merchantGroupGoods.getMerchantId(), merchantId);
//        merchantGroupGoodsService.delete(merchantGroupGoods);
//        return ReturnBody.success();
//    }


    @ApiOperation("订单列表")
    @PostMapping("orderList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String orderList(PageInfo pageInfo, String orderNum, Long usId, Integer status) {
        Long id = (Long) request.getAttribute("id");
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getParentId() != -1) {
            MerchantInfo parentInfo = merchantInfoService.getOneForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.US_ID, merchantInfo.getParentId()));
            id = parentInfo.getId();
        }
        pageInfo.setTimeScreen("create_time");
        pageInfo.setDefaultSort("create_time", SortWay.DESC);
        //执行分页辅助工具
        Long finalId = id;
        PageResult<UsGroupGoodsOrder> pageResult = new PageUtil<UsGroupGoodsOrder>(pageInfo).startPage((page, queryWrapper) -> {
//            if (CommUtil.checkNull(type)) {
//                queryWrapper.eq(UsGroupGoodsOrder.TYPE, type);
//            }
            if (CommUtil.checkNull(orderNum)) {
                queryWrapper.eq(UsGroupGoodsOrder.ORDER_NO, orderNum);
            }
            if (CommUtil.checkNull(usId)) {
                queryWrapper.eq(UsGroupGoodsOrder.US_ID, usId);
            }
            if (CommUtil.checkNull(status)) {
                queryWrapper.eq(UsGroupGoodsOrder.STATUS, status);
            }
            queryWrapper.eq(UsGroupGoodsOrder.MERCHANT_ID, finalId);
            usGroupGoodsOrderService.page(page, queryWrapper);
        });
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("订单详情")
    @PostMapping("orderDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = true),
    })
    @ParameterVerify(notNull = "orderNum")
    public String orderDetail(String orderNum) {
        Long merchantId = (Long) request.getAttribute("id");
        JSONObject object = new JSONObject(true);
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>().eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGroupGoodsOrder) || !merchantId.equals(usGroupGoodsOrder.getMerchantId())) {
            return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
        }
        object.put("order", usGroupGoodsOrder);
        if (usGroupGoodsOrder.getType() == 1 || usGroupGoodsOrder.getType() == 3) {
            UsAddress usAddress = usAddressService.getByIdForUpdate(usGroupGoodsOrder.getAddressId());
            object.put("address", usAddress);
        }
        UsInfo usInfo = usInfoService.getByIdForUpdate(usGroupGoodsOrder.getUsId());
        object.put("nick", usInfo.getNick());
        object.put("avatar", usInfo.getAvatar());
        //售后相关
        List<UsAfterSaleApply> usAfterSaleApplies = usAfterSaleApplyService.listForUpdate(new QueryWrapper<UsAfterSaleApply>().eq(UsAfterSaleApply.ORDER_NUM, usGroupGoodsOrder.getOrderNo()).orderByDesc(UsAfterSaleApply.CREATE_TIME));
        if (!usAfterSaleApplies.isEmpty()) {
            object.put("afterSale", usAfterSaleApplies.get(0));
        }
        return ReturnBody.success(object);
    }


    @ApiOperation("区域列表")
    @PostMapping("locationList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String locationList() {
        String location = "location";
        if (redisUtil.hasKey(location)) {
            List<SysLocation> list = (List<SysLocation>) redisUtil.get(location);
            return ReturnBody.success(list);
        } else {
            List<SysLocation> list = sysLocationService.list();
            redisUtil.set(location, list);
            return ReturnBody.success(list);
        }
    }

    @ApiOperation("获取区域分级tree")
    @PostMapping("locationTree")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String locationTree() {
        String locationTree = "locationTree";
        if (redisUtil.hasKey(locationTree)) {
            List<SysLocationTreeVO> tree = (List<SysLocationTreeVO>) redisUtil.get(locationTree);
            return ReturnBody.success(tree);
        } else {
            List<SysLocationTreeVO> tree = sysLocationService.tree();
            redisUtil.set(locationTree, tree);
            return ReturnBody.success(tree);
        }
    }


    @ApiOperation("发货")
    @PostMapping("delivery")
    public String delivery(String orderNum, String expressNumber, Integer type) {
        Long merchantId = (Long) request.getAttribute("id");
        UsGroupGoodsOrder usGroupGoodsOrder = usGroupGoodsOrderService.getOneForUpdate(new QueryWrapper<UsGroupGoodsOrder>()
                .eq(UsGroupGoodsOrder.ORDER_NO, orderNum));
        if (!CommUtil.checkNull(usGroupGoodsOrder)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (usGroupGoodsOrder.getType() == 0) {
            return ReturnBody.error("自提单不需发货，已通知用户自提");
        }
        CheckUtil.merchantCheck(merchantId, usGroupGoodsOrder.getMerchantId());
        if (usGroupGoodsOrder.getStatus() != 1) {
            return ReturnBody.error("状态错误");
        }
        if (usGroupGoodsOrder.getAfterSaleStatus() != 0) {
            return ReturnBody.error("该订单正在申请退款或已退款完成，无法发货");
        }
        usGroupGoodsOrder.setStatus(2);
        if (type == 1) {
            if (!CommUtil.checkNull(expressNumber)) {
                return ReturnBody.error("快递单号不可为空");
            }
            usGroupGoodsOrder.setExpressNumber(expressNumber);
        }
        usGroupGoodsOrderService.delivery(usGroupGoodsOrder);

        return ReturnBody.success();
    }

}
